package com.hxh.component.business.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hxh.component.basicore.component.imageLoader.IImageLoader;
import com.hxh.component.basicore.component.imageLoader.ImageFactory;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.business.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * author mardawang
 * <p>
 * email:wy363681759@163.com
 * <p>
 * date: 2018/3/16
 * <p>
 * desc:
 */

public class BannerImg extends FrameLayout {
    private static final boolean isAutoPlay = true;
    private List<String> imageUris;
    private List<Integer> imageUris_int;
    private List<ImageView> imageViewsList;
    private List<ImageView> dotViewsList;
    private LinearLayout mLinearLayout;
    private ViewPager mViewPager;
    private int currentItem;
    private IImageLoader.Options mOptions;
    private ScheduledExecutorService scheduledExecutorService;
    private BannerImg.OnImageClickListener mOnlistener;
    @SuppressLint({"HandlerLeak"})
    private Handler handler;
    private int errorResId;

    public BannerImg(Context context) {
        this(context, (AttributeSet) null);
    }

    public BannerImg(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerImg(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.currentItem = 0;
        this.handler = new Handler() {
            public void handleMessage(Message msg) {
                if (!isInEditMode()) {
                    super.handleMessage(msg);
                    mViewPager.setCurrentItem(currentItem);
                }
            }
        };
        this.init(context);
    }

    private void init(Context context) {
        if (!this.isInEditMode()) {
            this.mOptions = IImageLoader.Options.defaultOptions();
            this.initUI(context);
            if (this.imageUris.size() > 0) {
                this.setImageUris(this.imageUris);
            }

            this.startPlay();
        }

    }

    private void initUI(Context context) {
        if (!this.isInEditMode()) {
            this.imageViewsList = new ArrayList();
            this.dotViewsList = new ArrayList();
            this.imageUris = new ArrayList();
            this.imageUris_int = new ArrayList();
            LayoutInflater.from(context).inflate(com.hxh.component.basicore.R.layout
                    .layout_bannerimg, this, true);
            this.mLinearLayout = (LinearLayout) this.findViewById(com.hxh.component.basicore.R.id
                    .dotsImg);
            this.mViewPager = (ViewPager) this.findViewById(com.hxh.component.basicore.R.id
                    .imagePager);
        }

    }

    public void clearUris() {
        if (this.imageUris != null) {
            this.imageUris.clear();
        }

    }

    public void setImageUris(List<String> imageuris) {
        this.setImageUris(imageuris, ImageView.ScaleType.FIT_XY);
    }

    public void setImageUris(List<String> imageuris, ImageView.ScaleType scaleType) {
        int i;
        for (i = 0; i < imageuris.size(); ++i) {
            this.imageUris.add(imageuris.get(i));
        }

        for (i = 0; i < this.imageUris.size(); ++i) {
            ImageView imageView = new ImageView(this.getContext());
            imageView.setScaleType(scaleType);
            this.imageViewsList.add(imageView);
            ImageFactory.getGlideLoader().loadFormNet(imageView, (String) imageuris.get(i),
                    mOptions);

            if (this.imageUris.size() > 1) {
                ImageView viewDot = new ImageView(this.getContext());
                int width = Utils.Dimens.dpToPxInt(8.0F);
                int height = Utils.Dimens.dpToPxInt(8.0F);
                FrameLayout.LayoutParams params = new LayoutParams(width, height);
                params.leftMargin = Utils.Dimens.dpToPxInt(6);
                viewDot.setLayoutParams(params);
                if (i == 0) {
                    viewDot.setImageResource(R.mipmap.dot_focus);
                } else {
                    viewDot.setImageResource(R.mipmap.dot);
                }

                this.dotViewsList.add(viewDot);
                this.mLinearLayout.addView(viewDot);
            }
            imageView.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (null != mOnlistener) {
                        mOnlistener.onClick(currentItem);
                    }

                }
            });
        }

        this.mViewPager.setFocusable(true);
        this.mViewPager.setAdapter(new MyPagerAdapter());
        this.mViewPager.setOnPageChangeListener(new MyPageChangeListener());
    }

    public void setImageUris(String imageuris) {
        this.imageUris.add(imageuris);
        this.setImageUris(this.imageUris);
    }

    public void setImageUris_Resource(List<Integer> imageuris) {
        for (int i = 0; i < imageuris.size(); ++i) {
            this.imageUris_int.add(imageuris.get(i));
        }

        this.showBanner();
    }

    private void showBanner() {
        for (int i = 0; i < this.imageUris_int.size(); ++i) {
            ImageView imageView = new ImageView(this.getContext());
            LayoutParams layoutParams = new LayoutParams(Utils.Dimens.dpToPxInt(15), Utils.Dimens
                    .dpToPxInt(15));
            layoutParams.leftMargin = Utils.Dimens.dpToPxInt(10);
            imageView.setLayoutParams(layoutParams);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            this.imageViewsList.add(imageView);
            ImageFactory.getGlideLoader().loadResource(imageView, ((Integer) this.imageUris_int
                    .get(i)).intValue(), mOptions);

            ImageView viewDot = new ImageView(this.getContext());
            int width = Utils.Dimens.dpToPxInt(8.0F);
            int height = Utils.Dimens.dpToPxInt(8.0F);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
            params.leftMargin = Utils.Dimens.dpToPxInt(6);
//            params.rightMargin = 6;
            viewDot.setLayoutParams(params);
            if (i == 0) {
                viewDot.setImageResource(R.mipmap.dot_focus);
            } else {
                viewDot.setImageResource(R.mipmap.dot);
            }

            this.dotViewsList.add(viewDot);
            this.mLinearLayout.addView(viewDot);
            imageView.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (null != mOnlistener) {
                        mOnlistener.onClick(currentItem);
                    }

                }
            });
        }

        this.mViewPager.setFocusable(true);
        this.mViewPager.setAdapter(new MyPagerAdapter());
        this.mViewPager.setOnPageChangeListener(new MyPageChangeListener());
    }

    public void setImageUris_Resource(Integer img) {
        this.imageUris_int.add(img);
        this.showBanner();
    }

    public void setOnClickListener(BannerImg.OnImageClickListener lis) {
        this.mOnlistener = lis;
    }

    private void startPlay() {
        this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        this.scheduledExecutorService.scheduleAtFixedRate(new BannerTask(), 3L, 2L, TimeUnit
                .SECONDS);
    }

    private void stopPlay() {
        this.scheduledExecutorService.shutdown();
    }

    private void setImageBackground(int selectItems) {
        for (int i = 0; i < this.dotViewsList.size(); ++i) {
            if (i == selectItems) {
                ((ImageView) this.dotViewsList.get(i)).setImageResource(com.hxh.component
                        .basicore.R.mipmap.dot_focus);
            } else {
                ((ImageView) this.dotViewsList.get(i)).setImageResource(com.hxh.component
                        .basicore.R.mipmap.dot);
            }
        }

    }

    public void setErrorImgResId(int errorId) {
        errorResId = errorId;
        mOptions = new IImageLoader.Options(errorResId, errorResId);
    }

    private class BannerTask implements Runnable {
        private BannerTask() {
        }

        public void run() {
            synchronized (mViewPager) {
                currentItem = (currentItem + 1) % imageViewsList.size();
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        boolean isAutoPlay;

        private MyPageChangeListener() {
            this.isAutoPlay = false;
        }

        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 0:
                    if (BannerImg.this.mViewPager.getCurrentItem() == mViewPager.getAdapter()
                            .getCount() - 1 && !this.isAutoPlay) {
                        mViewPager.setCurrentItem(0);
                    } else if (mViewPager.getCurrentItem() == 0 && !this.isAutoPlay) {
                        mViewPager.setCurrentItem(mViewPager.getAdapter().getCount() - 1);
                    }
                    break;
                case 1:
                    this.isAutoPlay = false;
                    break;
                case 2:
                    this.isAutoPlay = true;
            }

        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageSelected(int pos) {
            setImageBackground(pos);
        }
    }

    private class MyPagerAdapter extends PagerAdapter {
        private MyPagerAdapter() {
        }

        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView((View) imageViewsList.get(position));
        }

        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView((View) imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        public int getCount() {
            return imageViewsList.size();
        }

        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        public Parcelable saveState() {
            return null;
        }
    }

    public interface OnImageClickListener {
        void onClick(int var1);
    }
}
